package com.xyzwps.paimon.furina.modules.me

import com.xyzwps.paimon.furina.common.JsonResponse
import com.xyzwps.paimon.furina.common.hf
import com.xyzwps.paimon.furina.infra.*
import com.xyzwps.paimon.furina.middleware.AuthMW
import org.springdoc.webmvc.core.fn.SpringdocRouteBuilder.route
import org.springframework.stereotype.Component
import org.springframework.web.servlet.function.RouterFunction
import org.springframework.web.servlet.function.ServerRequest
import org.springframework.web.servlet.function.ServerResponse

@Component
class MeApis(
    private val meApp: MeApplication,
    authMW: AuthMW
) {

    private val shouldAuth = authMW::shouldAuth

    companion object {
        const val TAG = "Me"
    }

    fun router(): RouterFunction<ServerResponse> = route()
        .GET("", hf(shouldAuth, handler = ::getMe)) {
            it.tag(TAG)
                .operationId("get-me")
                .summary("Get me")
                .desc(shouldAuth = true)
                .respOK(RichMeInfoDTO::class.java)
        }
        .PATCH("/info", acceptJson, hf(shouldAuth, handler = ::updateMeUserInfo)) {
            it.tag(TAG)
                .operationId("update-my-info")
                .summary("Update info of me")
                .desc(shouldAuth = true)
                .reqBody(UpdateMeUserInfoPayload::class.java)
                .respOK(RichMeInfoDTO::class.java)
        }
        .build()

    private fun getMe(req: ServerRequest): JsonResponse = JsonResponse().body(meApp.getRichMeInfo(req.userId))

    private fun updateMeUserInfo(req: ServerRequest): JsonResponse {
        val body = req.validatedBody<UpdateMeUserInfoPayload>()
        return JsonResponse().body(meApp.updateMeUserInfo(req.userId, body))
    }
}